#include "app_message.h"
#include <stdlib.h>
#include <string.h>
#include "cJSON/cJSON.h"
#include "log/log.h"
#include "app_common.h"

char *app_message_charsToJson(char *chars, int len){
    // 将字符数组转换为json字符串
    // 1、从chars中提取出conn_type、id_len、msg_len、id、msg
    int conn_type = (int)chars[0];
    int id_len = (int)chars[1];
    int msg_len = (int)chars[2];
    // chars_len 长度判断
    if (len != 3 + id_len + msg_len)
    {
        log_error("字符数组长度不正确");
        return NULL;
    }
    char id[id_len];
    char msg[msg_len];
    memcpy(id, chars + 3, id_len);
    memcpy(msg, chars + 3 + id_len, msg_len);

    // 2、将提取出的id、msg数据转换为十六进制字符串
    char *id_hex = app_common_charsToHexstr(id, id_len);
    char *msg_hex = app_common_charsToHexstr(msg, msg_len);

    // 3、将conn_type、id、msg转换为json字符串
    cJSON *root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "conn_type", conn_type);
    cJSON_AddStringToObject(root, "id", id_hex);
    cJSON_AddStringToObject(root, "msg", msg_hex);
    char *json = cJSON_PrintUnformatted(root);

    // 4、释放内存
    cJSON_Delete(root);
    free(id_hex);
    free(msg_hex);

    return json;
}

int app_message_jsonToChars(char *json, char *chars_buf, int buf_size)
{
    // 将json字符串转换为字符数组
    // 1、解析json字符串
    cJSON *root = cJSON_Parse(json);
    int conn_type = cJSON_GetObjectItem(root, "conn_type")->valueint;
    char *id = cJSON_GetObjectItem(root, "id")->valuestring;
    char *msg = cJSON_GetObjectItem(root, "msg")->valuestring;

    // 2、将解析出的数据转换为conn_type、id_len、msg_len、id、msg
    int id_len = -1;
    int msg_len = -1;
    char *id_chars = app_common_hexstrToChars(id, &id_len);
    char *msg_chars = app_common_hexstrToChars(msg, &msg_len);

    // 计算字符数组长度
    int chars_len = 3 + id_len + msg_len;
    if (chars_len > buf_size)
    {
        log_error("buf_size is too small");
        return -1;
    }

    // 3、将conn_type、id_len、msg_len、id、msg转换为字符数组
    chars_buf[0] = conn_type;
    chars_buf[1] = id_len;
    chars_buf[2] = msg_len;
    memcpy(chars_buf + 3, id_chars, id_len);
    memcpy(chars_buf + 3 + id_len, msg_chars, msg_len);

    // 4、释放内存
    cJSON_Delete(root);
    free(id_chars);
    free(msg_chars);

    return chars_len;
}
